package cn.jhz.learn.community_dynamic.wbms.controller.api;

import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import cn.jhz.learn.community_dynamic.CommunityDynamicApplication;
import cn.jhz.learn.community_dynamic.common.bean.JsonData;
import cn.jhz.learn.community_dynamic.common.exception.RequestException;
import cn.jhz.learn.community_dynamic.dao.ImageJpaRepository;
import cn.jhz.learn.community_dynamic.dao.PostJpaRepository;
import cn.jhz.learn.community_dynamic.dao.UserJpaRepository;
import cn.jhz.learn.community_dynamic.manager.FileManager;
import cn.jhz.learn.community_dynamic.model.ImageEntity;
import cn.jhz.learn.community_dynamic.service.ImageService;
import lombok.Getter;

@RestController
@RequestMapping("api/")
public class AuthImageController {
    private final ImageJpaRepository imageJpaRepository;
    private final PostJpaRepository postJpaRepository;
    private final UserJpaRepository userJpaRepository;
    private final ImageService imageService;
    private final FileManager fileManager;
    
    @Getter
    private class ImageView {
	private Integer id;
	private Long userId;
	private String url;
        private Date createTime;
        private Byte status;
        
        private ImageView(ImageEntity entity) {
	    super();
	    this.id = entity.getId();
	    this.userId = entity.getUser().getLoginId();
	    this.url = entity.getUrl();
	    this.createTime = entity.getCreateTime();
	    this.status = entity.getStatus();
	}
    }
    
    @Autowired
    public AuthImageController(ImageJpaRepository imageJpaRepository, PostJpaRepository postJpaRepository, UserJpaRepository userJpaRepository, ImageService imageService, FileManager fileManager) {
	super();
	this.imageJpaRepository = imageJpaRepository;
	this.postJpaRepository = postJpaRepository;
	this.userJpaRepository = userJpaRepository;
	this.imageService = imageService;
	this.fileManager = fileManager;
    }

    @GetMapping("auth/wbms/image/all")
    @PreAuthorize("hasAuthority('image::get_all')")
    public JsonData getAll(@RequestParam("page") Integer page, @RequestParam("size") Integer size) {
	return JsonData
		.newSuccessInstance(this.imageJpaRepository.findAll(PageRequest.of(page - 1, size)).map(this::adpt));
    }

    @GetMapping("auth/wbms/image/post/all/{post_id}")
    @PreAuthorize("hasAuthority('image::get_all_post')")
    public JsonData getAllByPostId(@PathVariable("post_id") Integer postId) {
	return JsonData.newSuccessInstance(this.postJpaRepository.findById(postId).orElseThrow(() -> new RequestException("无效文章")).getImages().stream().map(this::adpt).collect(Collectors.toList()));
    }

    @GetMapping("auth/wbms/image/user/all/{user_id}")
    @PreAuthorize("hasAuthority('image::get_all_user')")
    public JsonData getAllByUser(@PathVariable("user_id") Long userId) {
	return JsonData.newSuccessInstance(this.userJpaRepository.findByLoginId(userId).orElseThrow(() -> new RequestException("无效用户")).getImages().stream().map(this::adpt).collect(Collectors.toList()));
    }


    @GetMapping("auth/wbms/image/review/all")
    @PreAuthorize("hasAuthority('image::get_all_review')")
    public JsonData getAllReview(@RequestParam("size") Integer size) {
	return JsonData.newSuccessInstance(this.imageService.getReviewCache(CommunityDynamicApplication.REVIEW_CACHE)
		.get().stream().map(this.imageJpaRepository::findById).map(Optional::get).map(this::adpt).limit(size)
		.collect(Collectors.toList()));
    }

    @PatchMapping(value = "auth/wbms/image/status", consumes = "application/x-www-form-urlencoded")
    @PreAuthorize("hasAuthority('image::patch')")
    public JsonData patch(@RequestParam("id") Integer id, @RequestParam("operate") Byte operate,
	    @RequestParam(value = "review") Boolean review) {

	if (review) {
	    List<Integer> cache = this.imageService.getReviewCache(CommunityDynamicApplication.REVIEW_CACHE).get();
	    cache.remove(id);
	    this.imageService.putReviewCache(CommunityDynamicApplication.REVIEW_CACHE, cache);
	}

	return JsonData.newSuccessInstance(this.adpt(this.fileManager.updateInstanceColumn(
		this.imageJpaRepository.findById(id).orElseThrow(() -> new RequestException("图片不存在")), operate)));
    }

    private ImageView adpt(ImageEntity entity) {
	ImageView view = this.new ImageView(entity);
	return view;
    }
}
